<template>
  <div v-if="!ill" style="padding-bottom:48px;" :class="{isHeadHide:!$root.ISAPP}">
    <v-header v-if="!$root.ISAPP">
      <div class="nav-tab2">
        <h3>订单结算</h3>
      </div>
    </v-header>
    <!--收货地址  -->
    <UserAddressUint :addressUnit="userDefaultAddress" :addressType="1"></UserAddressUint>
    <!-- 身份证号 -->
    <div v-show="curExp.isneedidcard" class="check_ems flex-between">
      <p>身份证号：</p>
      <p class="exp-cardnum">
        <input type="text" placeholder="海外物流订单需填写收货人身份证号" @input="inputCardnum">
      </p>
    </div>
    <!--订单 单元  -->
    <!-- <OrderUnit :orderInfo="getOrder" :truePay="getOrder._allPay" :cutchecktype='1'></OrderUnit> -->
    <div class="order_unit padding">
      <section class="cart_head">
        <div class="ellipsis flex-aic flex">
          <i
            class="tilt"
            :class="getOrder.businesstype===3?'ico-sp-store':(getOrder.businesstype===2?'ico-sp-buy':'ico-sp-official')"
          ></i>
          <span class="busName">{{getOrder.businessname}}</span>
          <!-- <p class="padding flex-center inline-block">
                    <span  class="rights_icon">{{getOrder.sendplace}}</span>
          </p>-->
        </div>
        <div class="status_order ellipsis">{{getOrder.sendplace}}</div>
      </section>
      <section>
        <div
          class="flex-aic cart_content"
          v-for="(item,index) in getOrder.productitems"
          :key="index"
        >
          <div class="img_box_img">
            <img v-lazy="https(item.productimgurl)" alt>
          </div>
          <div class="cart_info">
            <div>
              <p class="ellipsis" style="width:70%;">{{item.productname}}</p>
              <p>
                单价¥{{item.payprice|tofixed}}
                <span v-if="item.cutminprice">
                  可砍至：
                  <em class="cutminprice">¥{{item.cutminprice|tofixed}}</em>
                </span>
                <span
                  v-else-if="item.payprice!=item.saleprice"
                  class="tex_in"
                >&nbsp;&nbsp;¥{{item.saleprice|tofixed}}</span>
              </p>
              <p class="overcount">{{item.color}} ,{{item.size}} , x{{item.count}}</p>
            </div>
          </div>
        </div>
      </section>
      <section class="flex check_footer">
        <p>共{{getOrder.quantity}}件商品</p>
        <div class>
          <p class="flex-between">
            <span>商品总额:</span>
            <span>¥{{getOrder.productmoney|tofixed}}</span>
          </p>
          <p class="flex-between">
            <span>运费:</span>
            <span>¥{{getOrder.expressfee|tofixed}}</span>
          </p>
          <p class="flex-between" v-if="getOrder.cutmoney">
            <span>助力砍价:</span>
            <span>¥{{getOrder.cutmoney|tofixed}}</span>
          </p>
          <p class="flex-between">
            <span>总计:</span>
            <span>¥{{(getOrder.productmoney+getOrder.expressfee)|tofixed}}</span>
          </p>
        </div>
      </section>
    </div>
    <!-- 选择物流 -->
    <div class="check_ems" v-show="userDefaultAddress && userDefaultAddress.addressid">
      <div class="flex-between exp-info">
        <p>选择物流方式</p>
        <p class="flex-center">
          <span>{{curExp.name}}</span>
        </p>
      </div>
      <div class="exp-list">
        <div
          class="flex-between express_unit"
          v-for="(item,c) in ExpressList"
          :key="item.expresstemplateitemid"
          @click="seleExpress(item,c)"
        >
          <p class="flex-center exp_name">
            <span class="icon_cartSel" :class="{icon_cartSeled:item.isselected}"></span>
            <span>{{item.name}}</span>
          </p>
          <p>¥{{item.expressfee | tofixed}}</p>
        </div>
      </div>
    </div>
    <!--选择优惠券  -->
    <div class="check_coupons" @click.stop="goCoupon">
      <div class="flex-between">
        <p>
          选择优惠:
          <span
            v-if="hasCoupon&&discounts.isusecoup&&(getOrder.productmoney-hasCoupon>0)"
          >本券共为您节省</span>
        </p>
        <p>
          <span v-if="!discounts.isusecoup" style="color:#999">不使用优惠</span>
          <span
            v-else-if="!hasCoupon||hasCoupon<=0|| (getOrder.productmoney-hasCoupon<=0)"
          >您当前没有可用优惠券</span>
          <span v-else-if="hasCoupon>0&& (getOrder.productmoney-hasCoupon>0)">-¥{{hasCoupon}}</span>
          <!-- <span v-else-if="!hasCoupon&& queryOrder.ordertype!=0||hasCoupon<=0|| (getOrder.productmoney-hasCoupon<=0)">您当前没有可用优惠券</span> -->
          <!-- <span v-else-if="queryOrder.ordertype!=0 || (getOrder.productmoney-hasCoupon<0)" style="color:#999">优惠券不可用</span> -->
          <span class="right_icon"></span>
        </p>
      </div>
      <!-- <div class="order_coulist" v-if="getOrder.productmoney-hasCoupon>0">
        <p @click.stop="cancelCou" v-if="hasCoupon&&useCou">有钱任性，我就是不用优惠券</p>
      </div>-->
      <!-- <p class="buy_tip" v-if="getOrder.hasSpecial">温馨提示：此订单中有商品参与鬼市活动，由于您未获得鬼市购买资格，只能以原价购买</p> -->
    </div>
    <!-- 买家留言 -->
    <div class="usermemo">
      <label for>买家留言:</label>
      <textarea name id placeholder="选填:对本次交易的说明" v-model="usermemo"></textarea>
    </div>
    <!--底部  -->
    <div class="flex-between flex-center o_footer">
      <p>
        <!-- <span>共{{getOrder.count}}件商品</span> -->
        <span>
          总计：
          <span class="pay_color">¥{{(getOrder.paymoney||0) | tofixed}}</span>
        </span>
      </p>
      <mt-button class="btn_total" @click="payment">提交订单</mt-button>
    </div>

    <Pay v-if="payOrderno" :payorderno="payOrderno" :model="true"></Pay>
  </div>
  <div v-else></div>
</template>
<script>
import { mapGetters } from "vuex";
import UserAddressUint from "../templates/user/UserAddressUnit";
import CouponUnit from "../templates/CouponUnit";
import Pay from "../pay/Pay";

import { NewOrderAdd, AddOrderZone } from "../../common/api/order";
import { AddressDefault } from "../../common/api/user";
import { saveOrderno } from "../../common/api/distribution";
import { NewOrderCheck } from "../../common/api/product";

var opt = {
  common: 0,
  group: 1,
  tuxedo: 2,
  cut: 3
}; // int 订单操作类型 0 - 普通，1 - 开团，2 - 参团，3 - 砍价",


export default {
  data() {
    return {
      expressTemplate: [],
      address: {},
      hasAddress: false,
      // userDefaultAddress: {},
      postdata: {},
      defaultCoupon: {},
      couvalue: 0,
      useCou: false,
      couponuseid: "",
      couponType: "",
      expressDate: [],
      getOrder: {},
      cardnum: "",
      usermemo: "",
      // ucp: true,
      queryOrder: {},
      ExpressList: {},
      curExp: {},

      payOrderno: ""
    };
  },
  components: {
    // OrderUnit,
    UserAddressUint,
    CouponUnit,
    Pay
  },
  computed: {
    ...mapGetters({
      insq: "insq",
      orderItem: "orderItem",
      user: "userInfo",
      userAddressList: "userAddressList",
      expressT: "expressT",
      fromType: "fromType", // 0订单来之购物车 1来之详情立即购买
      userDefaultAddress: "userDefaultAddress",
      discounts: "discounts", // 优惠 和红包id
      payingOrder: "payingOrder"
    }),
    ill() {
      return !(this.insq || this.user.token);
    },
    hasCoupon() {
      let _ = this;
      let totleCou = 0;
      let con = _.getOrder.coupon;
      if (_.getOrder && con) {
        totleCou = Number(con.discountmoney) ? Number(con.discountmoney) : 0;
      }
      return totleCou;
    }
  },
  beforeRouteEnter(to, from, next) {
    next(vm => {
      // 通过 `vm` 访问组件实例
      if (
        from.path.indexOf("user/address") > -1 ||
        from.path.indexOf("user/editAddress") > -1 ||
        from.path.indexOf("productDetail") > -1
      ) {
        // vm.GetExpress();
      }
    });
  },
  beforeRouteLeave(to, from, next) {
    if (to.path !== "/user/address"&&to.path!='/order/coupon')
      this.confirm({
        title: "",
        msg: "离开宝贝会被别人抢走哦~",
        okText: "我再想想",
        ok: () => {
          next(false);
        },
        cancelText: "去意已决",
        cancel: () => {
          next();
        }
      });
    else next();
  },
  beforeMount() {
    let _ = this,
      { payingOrder, ill } = _;

    if (payingOrder) {
      _.$store.dispatch("updPayingOrder", "");
      _.$router.replace("/paysuccess/" + payingOrder);
      return
    }
    // this.GetExpress()
    if (ill) _.$router.go(-1);
    _.$route.query.productitems = JSON.parse(
      decodeURIComponent(_.$route.query.productitems)
    );
    _.queryOrder = { ..._.$route.query, ..._.queryOrder };
    // console.log("结算 地址栏参数", this.queryOrder);
    // console.log("discounts------>", _.discounts);
  },
  mounted() {
    let _ = this;
    _.newCheck();
    setTimeout(() => {
      if (!_.getOrder.paymoney) {
        _.newCheck();
      }
    }, 800);
    if (!(_.userDefaultAddress && _.userDefaultAddress.mobile)) {
      if (_.user.token) _.GetAddressDefault();
      else {
        setTimeout(() => {
          _.GetAddressDefault();
        }, 800);
      }
    }
    console.log("userDefaultAddress", this.userDefaultAddress);
    _.mtaReport("ddjs_yemian_bg");
  },
  methods: {
    newCheck() {
      let _ = this;
      let opt = {
        // 用户地址id
        addressid: _.userDefaultAddress.addressid || "",
        // "物流模板子项id",
        expresstemplateitemid: _.curExp.expresstemplateitemid || "",
        productitems: _.queryOrder.productitems,
        // 红包id
        redpacketids: _.discounts.redpacket || [],
        // 优惠券id
        couponuserid: _.discounts.couponuserid || "",
        // 订单类型
        ordertype: _.queryOrder.ordertype,
        // 扩展id
        extendid: _.queryOrder.extendid,
        usecoupon: _.discounts.isusecoup
      };

      // console.log("opt" , opt)
      NewOrderCheck(opt)
        .then(res => {
          if (res) {
            _.getOrder = res;
            // _.$store.dispatch("setExpressTemplate", res.expresslist);
            _.queryOrder.expresstemplateitemid = _.curExp.expresstemplateitemid;
            console.log("下单信息----=============", res);
            // if (res.coupondiscountmoney || res.redpacketdiscountmoney) {
            //   _.useCou = true;
            // }
            let co = _.discounts;
            if (res.coupon && res.coupon.discountmoney > 0) {
              co.redpacket = res.coupon.redpacket;
              co.couponuserid = res.coupon.couponuserid;
              _.$store.dispatch("Discounts", co);
            }
            // else {
            //   this.ucp = false;
            // }
            if (res.expresslist) {
              _.ExpressList = res.expresslist;
              _.ExpressList.map(i => {
                if (i.isselected) {
                  _.curExp = { ...i };
                }
                return _.curExp;
              });
            }
          }
        })
        .catch(e => {
          console.error(e);
        });
    },
    seleExpress(item, index) {
      if (item.isselected) return;

      for (let i = 0; i < this.ExpressList.length; i++) {
        if (i == index) {
          this.ExpressList[i].isselected = true;
          this.curExp = { ...this.ExpressList[i] };
        } else {
          this.ExpressList[i].isselected = false;
        }
      }

      this.newCheck();
    },
    inputCardnum(e) {
      let val = e.target.value;
      val = val.replace(/\s|[^0-9xX]/g, "");
      let len = val.length;
      if (len > 18) val = val.slice(0, 18);
      if (len === 18)
        val = val.replace(/(\d{6})(\d{8})(\d{3}[0-9xX])/, "$1 $2 $3");
      else if (len === 15)
        val = val.replace(/(\d{6})(\d{6})(\d{2}[0-9xX])/, "$1 $2 $3");

      this.cardnum = val;
      e.target.value = val;
    },
    cancelCou() {
      this.useCou = false;
      this.queryOrder.redpacketids = [];
      this.queryOrder.couponuserid = "";
    },
    goCoupon() {
      let _ = this;
      let productitemids = [];
      for (let i = 0; i < _.queryOrder.productitems.length; i++) {
        productitemids.push(_.queryOrder.productitems[i].productitemid);
      }
      this.$router.push({
        path: "/order/coupon",
        query: {
          productmoney: this.getOrder.productmoney,
          productitemids: productitemids,
          type: 1,
          ordertype: this.queryOrder.ordertype
        }
      }); // B2C为1
    },
    payment() {
      // "idcard":"身份证号",
      // "addressid":"地址id",
      // "usermemo":"用户备注",
      // "expresstemplateitemid":"物流模板子项id",
      //  "productitems":[
      //     {
      //         "productitemid":"商品子项id",
      //         "count":"int 数量",
      //         "producttype":"int 商品类型",
      //         "distributionid":"分销商id",
      //         "parentid":"",
      //                "prostatus":"0 非准入门槛商品，1 准入门槛商品"
      //     }
      // ],
      // "redpacketids":[
      //     "redpacketid"
      // ],
      // "couponuserid":"String 优惠券id",
      // "ordertype":"int 订单操作类型 0 - 普通，1 - 开团，2 - 参团，3 - 砍价",
      // "extendid":"扩展id （根据ordertype和producttype决定具体类型的id：例：giftitemid、activityid、teamid、cuttingid)"
      let _ = this;
      //   var or = _.getOrder;

      var option = {
        // 收货人身份证号，物流模板isneedidcard为true时必须
        idcard: _.cardnum.replace(/\s/g, ""),
        // 用户地址id
        addressid: _.userDefaultAddress.addressid,
        // "用户备注",
        usermemo: _.usermemo,
        // "物流模板子项id",
        expresstemplateitemid: _.curExp.expresstemplateitemid,

        productitems: _.queryOrder.productitems,
        // 红包id
        redpacketids: _.discounts.redpacket || [],
        // 优惠券id
        couponuserid: _.discounts.couponuserid,
        // 订单类型
        ordertype: _.queryOrder.ordertype,
        // 扩展id
        extendid: _.queryOrder.extendid
      };

      if (option.addressid === "undefined" || !option.addressid) {
        _.toast("请添加收货地址");
        return;
      }
      if (
        option.expresstemplateitemid === "" ||
        !option.expresstemplateitemid
      ) {
        _.toast("没有运费模板暂时不能支付");
        return;
      }

      if (_.curExp.isneedidcard) {
        if (!/^(\d{14}|\d{17})[0-9xX]$/.test(option.idcard)) {
          _.toast("请输入正确的收货人身份证号");
          return;
        }
      }

      // console.log(_.getOrder,'kkk')
      if (_.getOrder.cutparamsType) {
        option.cuttingid = _.getOrder.cuttingid;
      }
      option.usermemo = this.usermemo;
      NewOrderAdd(option)
        .then(res => {
          window.TDH5SDK &&
            window.TDH5SDK.iap.placeOrder(
              res.orderno,
              option.paymoney,
              "CNY",
              option.items
            );

          _.report("订单结算-下单", "下单成功", res);
          _.mtaReport("ddjs_lijifukuan_dj", { result: "下单成功" });
          let itm =_.getOrder.productitems
          let co = this.discounts;
          co.isusecoup = true;
          co.redpacket = [];
          // 优惠券id  test
          co.couponuserid = "";
          this.$store.dispatch("Discounts", co);
          // console.log('orAdd', res)
          if (res && res.mustpay) {
            _.discounts.redpacket = [];
            // 优惠券id
            _.discounts.couponuserid = "";
            if (_.$root.ISAPP) {
              let opt = {
                name: "callAppPaymentPage",
                params: {
                  orderid: res.orderno,
                  callbackSuccessUrl: "",
                  callbackFailUrl: ""
                }
              };
              _.javascriptBridge(opt);
            } else {
              // let url = "/pay/" + res.orderno;
              // _.$router.replace(url);
              _.payOrderno = res.orderno;
            }
          }
        })
        .catch(e => {
          _.report("订单结算-下单", "下单失败", e);
          _.mtaReport("ddjs_lijifukuan_dj", { result: "下单失败" });

          console.error("订单添加失败", e);
          _.toast("订单添加失败：" + e.msg);
        });
    },
    GetAddressDefault() {
      AddressDefault({ token: this.user.token })
        .then(res => {
          console.log("默认地址", res);
          if (res) {
            res.mobile = res.mobile.split("-")[1];
            // this.userDefaultAddress = res
            this.$store.dispatch("setDefaultAddress", res);
          }
        })
        .catch(e => {
          console.error("获取默认地址失败", e);
        });
    }
  }
};
</script>
<style scoped>
.order_unit {
  padding: 0 10px;
  font-size: 12px;
  box-shadow: 0px 0px 8px rgba(219, 219, 219, 0.5);
  border-radius: 4px;
  margin: 15px 10px;
}
.cart_head {
  position: relative;
  border-bottom: 1px solid #fafafa;
  padding: 15px 0px;
}
.busName {
  font-size: 14px;
}
.cart_head .status_order {
  position: absolute;
  right: 0;
  top: 15px;
  width: 50%;
  text-align: right;
}
.check_ems,
.check_coupons {
  padding: 0 10px;
  /* height: 50px; */
  font-size: 14px;
  line-height: 50px;
  box-shadow: 0px 0px 8px rgba(219, 219, 219, 0.5);
  font-size: 14px;
  margin: 15px 10px;
}
.check_footer {
  -webkit-box-pack: justify;
  -webkit-justify-content: space-between;
  -ms-flex-pack: justify;
  justify-content: space-between;
  padding: 15px 0;
}
.check_footer p {
  margin-bottom: 10px;
}
.check_footer p > span:nth-of-type(1) {
  margin-right: 30px;
  display: inline-block;
  width: 71px;
  text-align: right;
}
.cart_content .img_box_img {
  position: relative;
  width: 23%;
  margin-right: 6px;
}
.tex_in {
  text-decoration: line-through;
}
.cart_content .cart_info {
  width: 70%;
}

.o_footer {
  width: 100%;
  height: 48px;
  position: fixed;
  bottom: 0;
  box-shadow: 0px 0px 8px rgba(219, 219, 219, 0.5);
  z-index: 39;
  background: #fff;
}

.o_footer p > span:nth-of-type(1) {
  font-size: 12px;
  margin: 0 20px;
}

.o_footer p > span:nth-of-type(2) {
  font-size: 14px;
}

.o_footer .btn_total {
  color: #fff;
  background: #333;
  font-size: 16px;
  height: 100%;
  width: 100px;
}

.order_coulist .order_cou_unit {
  width: 63%;
}

.order_coulist {
  text-align: right;
}
.buy_tip {
  text-align: left;
  color: #e26868;
  font-size: 12px;
  line-height: 16px;
  padding-bottom: 10px;
}

.exp-cardnum {
  width: 75%;
}
.exp-cardnum input {
  width: 100%;
  font-size: 16px;
}
.exp-cardnum input::-webkit-input-placeholder {
  color: #999;
  font-size: 12px;
}
.exp-cardnum input:-ms-input-placeholder {
  color: #999;
  font-size: 12px;
}
.exp-cardnum input:-moz-placeholder {
  color: #999;
  font-size: 12px;
}
.exp-cardnum input::-moz-placeholder {
  color: #999;
  font-size: 12px;
}

.exp-info {
  border-bottom: 1px solid #eee;
}
.exp-list {
  padding: 5px 0;
}
.express_unit {
  line-height: 40px;
}
.exp_name span:first-of-type {
  margin-right: 10px;
}
.usermemo {
  padding: 0 10px;
  box-shadow: 0px 0px 8px rgba(219, 219, 219, 0.5);
  font-size: 14px;
  margin: 15px 10px;
  text-align: left;
}
.usermemo label {
  float: left;
  height: 100%;
  margin-top: 15px;
  width: 20%;

  /* line-height: 100%; */
}
.usermemo textarea {
  /* float: left; */
  margin-top: 15px;
  width: 80%;
  background: none;
  outline-style: none;
  list-style: none;
}
</style>
